<template>
  <div>
    <Card>
      <Tables ref="tables" searchable search-place="top" :loading="listLoading" :columns="columns" v-model="list">
        <template slot="handleButton">
          <ButtonGroup>
            <Button v-if="serviceManager_btn_add" @click="handleAdd"><Icon type="md-add" />新增</Button>
            <Button v-if="serviceManager_btn_clientManager" @click="handlerClient"><Icon type="ios-send" />授权服务</Button>
            <Button v-if="serviceManager_btn_buidlProject" @click="handlerGenerator"><Icon type="ios-build" />构建工程</Button>
          </ButtonGroup>
        </template>
        <template slot="searchButton">
          <div style="float:right">
            <Input placeholder="输入关键字搜索" class="search-input" v-model="listQuery.name">
              <Button @click="getList" slot="append" type="info"  icon="ios-search"></Button>
            </Input>
          </div>
        </template>
        <template slot="action" slot-scope="props">
          <Button v-if="serviceManager_btn_edit" type="primary" @click="handleUpdate(props)" size="small">编辑</Button>
          <Divider type="vertical" />
          <Poptip confirm title="永久删除数据?" transfer @on-ok="handleDelete(props)">
            <Button v-if="serviceManager_btn_del" type="warning" size="small">删除</Button>
          </Poptip>
        </template>
      </Tables>
      <div style="margin: 10px;overflow: hidden">
        <div style="float: left;">
          <Page v-show="!listLoading" :total="total" :page-size-opts="[50,100,500,1000,2000]" :current="listQuery.page" show-total show-sizer :page-size="listQuery.limit" @on-change="handleCurrentChange" @on-page-size-change="handleSizeChange"></Page>
        </div>
      </div>
    </Card>
    <Modal :title="textMap[dialogStatus]" v-model="dialogFormVisible" :mask-closable='false' >
      <Form ref="form" :model="form" :label-width="100" :rules="rules">
        <FormItem label="服务编码" prop="code">
          <Input v-model="form.code"/>
        </FormItem>
        <FormItem label="服务密钥" prop="secret">
          <Input v-model="form.secret" />
        </FormItem>
        <FormItem label="服务名" prop="name">
          <Input v-model="form.name"/>
        </FormItem>
        <FormItem label="描述" prop="description">
          <Input v-model="form.description"/>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="cancel('form')">取消</Button>
        <Button type="primary" v-if="dialogStatus=='create'" @click="create('form')">确 定</Button>
        <Button type="primary" v-else @click="update('form')">确 定</Button>
      </div>
    </Modal>

    <Modal :title="dialogClientName" v-model="dialogClientVisible" :mask-closable='false' >
      <serviceClient :serviceId="currentId" @closeClientDialog="closeClientDialog" ref="serviceClient"></serviceClient>
    </Modal>

    <Modal :title="dialogProjectName" v-model="dialogProjectFormVisible">
      <Form :model="buildProjectForm" :rules="buildProjectFormRules" ref="buildProjectForm" :label-width="100">
        <FormItem label="package" prop="package">
          <Input v-model="buildProjectForm.package" placeholder="请输入工程包路径"></Input>
        </FormItem>
        <FormItem label="分布式事务">
          <i-switch :true-value="true" :false-value="false" :value="buildProjectForm.tx"></i-switch>
        </FormItem>
        <FormItem label="链路追踪">
          <i-switch :true-value="true" :false-value="false" :value="buildProjectForm.zipkin"></i-switch>
        </FormItem>
      </Form>
      <div slot="footer" class="dialog-footer">
        <Button @click="cancel('buildProjectForm')">取 消</Button>
        <Button type="primary" @click="buildProject('buildProjectForm')">确 定</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import Tables from '_c/tables'
import serviceClient from './client'
import { mapGetters } from 'vuex'
import {
  page,
  addObj,
  getObj,
  delObj,
  putObj,
  buildProject
} from '@/api/auth/service/index'
export default {
  name: 'user',
  components: {
    Tables,
    serviceClient
  },
  data () {
    return {
      form: {
        code: undefined,
        secret: undefined,
        name: undefined,
        description: undefined
      },
      buildProjectForm: {
        package: undefined,
        zipkin: 'false',
        tx: 'false'
      },
      buildProjectFormRules: {
        package: [
          {
            required: true,
            message: '请输入合法的包路径',
            trigger: 'blur'
          },
          {
            min: 3,
            message: '长度在 3个字符以上',
            trigger: 'blur'
          }
        ]
      },
      rules: {
        code: [
          {
            required: true,
            message: '请输入服务编码',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ],
        secret: [
          {
            required: true,
            message: '请输入服务密钥',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ],
        name: [
          {
            required: true,
            message: '请输入服务名',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ],
        description: [
          {
            required: true,
            message: '请输入描述',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ]
      },
      columns: [
        { title: 'id', key: 'id' },
        { title: '服务编码', key: 'code' },
        { title: '服务密钥', key: 'secret' },
        { title: '服务名', key: 'name' },
        { title: '描述', key: 'description' },
        { title: '创建时间', key: 'crtTime' },
        { title: '创建人姓名', key: 'crtName' },
        { title: '更新时间', key: 'updTime' },
        { title: '更新姓名', key: 'updName' },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          render: (h, params) => {
            return h(
              'div',
              this.$refs.tables.$scopedSlots.action(params)
            )
          }
        }
      ],
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        name: undefined
      },
      dialogFormVisible: false,
      dialogClientName: '授权服务',
      dialogProjectName: '初始化工程',
      dialogClientVisible: false,
      dialogProjectFormVisible: false,
      dialogStatus: '',
      serviceManager_btn_edit: false,
      serviceManager_btn_del: false,
      serviceManager_btn_add: false,
      serviceManager_btn_clientManager: false,
      textMap: {
        update: '编辑',
        create: '创建'
      },
      tableKey: 0,
      currentId: -1,
      currentName: undefined
    }
  },
  created () {
    this.getList()
    this.serviceManager_btn_edit = this.elements['serviceManager:btn_edit']
    this.serviceManager_btn_del = this.elements['serviceManager:btn_del']
    this.serviceManager_btn_add = this.elements['serviceManager:btn_add']
    this.serviceManager_btn_clientManager = this.elements['serviceManager:btn_clientManager']
    this.serviceManager_btn_buidlProject = this.elements['serviceManager:btn_buidlProject']
  },
  computed: {
    ...mapGetters([
      'elements'
    ])
  },
  methods: {
    handlerAddDepart () {
    },
    openDepartDialog () {
      this.dialogDepartVisible = true
    },
    closeDepartDialog (depart) {
      this.form.departName = depart.label
      this.form.departId = depart.id
      this.dialogDepartVisible = false
    },
    resetTemp () {
      this.form = {
        username: undefined,
        name: undefined,
        sex: '男',
        password: undefined,
        description: undefined,
        departId: undefined,
        departName: undefined,
        application: []
      }
    },
    handleUpdate (props) {
      getObj(props.row.id)
        .then(response => {
          this.form = response.data
          if (response.data.application) {
            this.form.application = response.data.application.split(',')
          } else {
            this.form.application = []
          }

          for (let i = 0; i < this.sexOptions.length; i++) {
            if (this.sexOptions[i].labelDefault === this.form.sex) {
              this.form.sex = this.sexOptions[i].value
            }
          }
          this.dialogFormVisible = true
          this.dialogStatus = 'update'
        })
    },
    getList (params) {
      this.listLoading = true
      page(this.listQuery)
        .then(response => {
          this.list = response.data.rows
          this.total = response.data.total
          this.listLoading = false
        })
    },
    create (formName) {
      const set = this.$refs
      set[formName].validate(valid => {
        if (valid) {
          addObj(this.form).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        } else {
          return false
        }
      })
    },
    update (formName) {
      const set = this.$refs
      set[formName].validate(valid => {
        if (valid) {
          this.dialogFormVisible = false
          this.form.password = undefined
          this.form.application = this.form.application.join(',')
          putObj(this.form.id, this.form).then(() => {
            this.dialogFormVisible = false
            this.getList()
            this.$Notice.success({
              title: '成功',
              desc: '修改成功'
            })
          })
        } else {
          return false
        }
      })
    },
    cancel (formName) {
      this.dialogProjectFormVisible = false
      this.$refs[formName].resetFields()
    },
    handleAdd () {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    handlerClient () {
      this.dialogClientVisible = true
      if (this.$refs.serviceClient !== undefined) {
        this.$refs.serviceClient.serviceId = this.currentId
        this.$refs.serviceClient.initClients()
      }
    },
    closeClientDialog () {
      this.dialogClientVisible = false
    },
    handlerGenerator () {
      this.dialogProjectFormVisible = true
    },
    buildProject (formName) {
      const set = this.$refs
      set[formName].validate(valid => {
        if (valid) {
          buildProject(
            this.currentId,
            this.buildProjectForm.package
          ).then(() => {
            const fileName = this.currentName + '.zip'
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href =
              '/api/auth/generator/build?id=' +
              this.currentId +
              '&packageName=' +
              this.buildProjectForm.package +
              '&token=' +
              getToken() +
              '&zipkin=' +
              this.buildProjectForm.zipkin +
              '&tx=' +
              this.buildProjectForm.tx
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放URL 对象
            document.body.removeChild(elink)
            this.dialogProjectFormVisible = false
          })
        }
      })
    },
    handleCurrentChange (val) {
      this.listQuery.page = val
      this.getList()
    },
    handleSizeChange (val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleDelete (params) {
      delObj(params.row.id)
        .then(() => {
          this.$Notice.success({
            title: '成功',
            desc: '删除成功'
          })
          this.getList()
        })
    },
    exportExcel () {
      this.$refs.tables.exportCsv({
        filename: `table-${(new Date()).valueOf()}.csv`
      })
    }
  }
}
</script>
